<?php

namespace app\common\model\worker;


use app\common\model\AreaModel;
use app\common\model\BaseModel;
use think\facade\Db;
class RecommendModel extends BaseModel
{
    protected $table = 'recommend';

    public function recommendCate()
    {
        return $this->belongsTo('app\common\model\worker\RecommendCateModel','cate_id','id')->field(['id,name']);
    }
    public function createAdmin()
    {
        return $this->belongsTo('app\common\model\AdminModel','action_admin_id','id')->field(['id,nickname']);
    }
    public function _formatInfo($info){
        $areaModel = new AreaModel();
        $areaText = $areaModel->getAreaName($info['area_code']);
        $info['area_text'] = $areaText;
        return $info;
    }

    public function _formatList($list){
        foreach ($list as $k=>$v){
            $list[$k] = $this->_formatInfo($v);
        }
        return $list;
    }

    /**
     * 添加推荐人
     * @param $data
     * @throws \Exception
     */
    public function add($data,$adminId)
    {
        $info = $this->where('recommend_mobile',$data['recommend_mobile'])->find();
        if(!empty($info)) exception('推荐人信息已经存在');
        Db::startTrans();
        $info = self::create($data);
        if(!$info){
            // 回滚事务
            Db::rollback();
            return false;
        }
        $authData = [
            'recommend_id'=>$info['id'],
            'role'=>'create',//创建者
            'admin_id'=>$adminId,
            'action_admin_id'=>$adminId,
            'action_time' => date('Y-m-d H:i:s')
        ];

        $res = RecommendAuthModel::create($authData);
        if(!$res){
            // 回滚事务
            Db::rollback();
            return false;
        }
        $actionLog = [
            'recommend_id'=>$info['id'],
            'action_log'=>json_encode($info),//创建者
            'remark'=>'add',
            'action_admin_id'=>$adminId,//操作人di
        ];
        $result = RecommendActionLogModel::create($actionLog);
        if(!$result){
            // 回滚事务
            Db::rollback();
            return false;
        }
        Db::commit();

        return true;

    }

    /**
     * 编辑推荐人
     * @param $data
     * @throws \Exception
     */
    public function edit($data)
    {
        $info = $this->where('recommend_mobile',$data['recommend_mobile'])->where('id','<>',$data['id'])->find();
        if(!empty($info)) exception('推荐人信息已经存在');
        return self::update($data);
    }

    public function getInfo($map){
        $info = $this->where($map)->find();
//        $areaModel = new AreaModel();
//        $areaText = $areaModel->getAreaName($info['area_code']);
//        $info['area_text'] = $areaText;
        return $info;
    }


    /**
     * 删除客户信息
     * @param $id
     */
    public function del($id){
        $this->where('id',$id)->delete();
        return true;
    }

}
